<?php
namespace app\api\controller\xilumarket;


use addons\xilumarket\controller\WeixinMini;
use app\common\controller\Api;
use app\common\library\Sms;
use app\common\model\DeliveryKeyUserRelation;
use app\common\model\xilumarket\FooterView;
use app\common\model\xilumarket\OrderDivide;
use app\common\model\xilumarket\Product as ProductModel;
use app\common\model\xilumarket\Third;
use app\common\model\xilumarket\TopicForum;
use app\common\model\xilumarket\TopicUser;
use app\common\model\xilumarket\UserAccount;
use app\common\model\xilumarket\UserAuth;
use app\common\model\xilumarket\UserCollection;
use app\common\model\xilumarket\UserFocus;
use fast\Random;
use think\Db;
use think\Exception;
use think\exception\PDOException;
use think\exception\ThrowableError;
use think\Hook;
use think\Validate;
use function fast\array_get;

/**
 * 用户模块控制器
 */
class User extends Api
{
    protected $noNeedLogin = ['wxlogin','get_mobile','mobilelogin','home','home_product','home_forum'];
    protected $noNeedRight = ['*'];

    public function _initialize()
    {
        parent::_initialize(); // TODO: Change the autogenerated stub

        Hook::add('user_register_successed', function ($user) {
            UserAccount::addAccount($user->id);
        });
    }

    /**
     * 微信登录
     * @ApiParams (name="code", type="string", required=true, description="微信登录code")
     * @ApiParams (name="platform", type="string", required=true, description="登录平台")
     */
    public function wxlogin()
    {
        $param = $this->request->only(['code','platform','puser_id']);
        $platform = array_get($param,'platform','wxmini');
        $wx = new WeixinMini();
        try {
            switch ($platform){
                case 'wxmini':
                    $config = \app\common\model\xilumarket\Config::getMyConfig('wxmini');
                    if(!$config || !$config['wxmini_appid'] || !$config['wxmini_appid']){
                        throw new Exception("请正确配置微信信息");
                    }
                    $data = $wx->wxlogin($param['code']);

                    $third = Third::where('platform',$platform)->where('openid',$data['openid'])->find();
                    if(!$third){
                        $third_data = [
                            'platform'      =>  $platform,
                            'user_id'       =>  0,
                            'openname'      => '',
                            'openid'        =>  $data['openid'],
                            'unionid'       =>  $data['unionid'] ?? '',
                            'access_token'  =>  $data['session_key'],
                            'logintime'     =>  time(),
                        ];
                        $third = Third::create($third_data);
                    }else{
                        $third_data = [
                            'access_token'  =>  $data['session_key'],
                            'unionid'      =>  $data['unionid'] ?? '',
                            'logintime'     =>  time()
                        ];
                        if($third->user_id>0){
                            $user = \app\common\model\User::get(['id'=>$third->user_id]);
                            if(!$user){
                                $third_data['user_id'] = 0;
                            }
                        }
                        $third->save($third_data);
                    }
                    if($third->user_id>0){
                        #模拟登陆
                        $this->auth->direct($user->id);
                        $data = ['userinfo' => $this->auth->getUserinfo()];
                        $data['third'] = ['third_id'=>$third->id,'openname'=>$third->openname,'binding'=>1];
                    }else{
                        $data = ['userinfo'=>[]];
                        $data['third'] = ['third_id'=>$third->id,'openname'=>$third->openname,'binding'=>0];
                    }
                    break;
                case 'wxpublic':

                    break;
            }
        }catch (ThrowableError $e){
            $this->error($e->getMessage());
        }catch (Exception $e){
            $this->error($e->getMessage());
        }
        $this->success('获取session_key成功',$data);

    }


    /**
     * @ApiTitle (获取手机号)
     * @ApiParams (name="third_id", type="int", required=true, description="第三方id")
     * @ApiParams (name="code", type="string", required=true, description="code")
     */
    public function get_mobile()
    {
        $param = $this->request->only(['third_id','code','puser_id']);
        $iv = $this->request->param('iv',null,null);
        $encryptedData = $this->request->param('encryptedData',null,null);
        $wx = new WeixinMini();
        $third = Third::where('id',array_get($param,'third_id'))->find();
        if(!$third) $this->error('未找到third数据',[],40001);
        if($third->user_id>0){
            $user = \app\common\model\User::get($third->user_id);
            if($user){
                $this->auth->direct($third->user_id);
                $third = ['third_id'=>$third->id,'binding'=>1];
                $this->success('手机号已经注册成功',['userinfo'=>$this->auth->getUserinfo(),'third'=>$third]);
            }
        }

        Db::startTrans();
        try {
            //新版本授权
            if($code = array_get($param,'code')){
                $data = $wx->getPhoneNumber($code);
            }else if($iv && $encryptedData){
                $data = $wx->wxEncrypted($third['access_token'],$iv,$encryptedData);
            }else{
                Db::rollback();
                throw new Exception("获取手机号参数错误");
            }
            if(!$data){
                Db::rollback();
                throw new Exception("获取手机号失败");
            }
            $user = \app\common\model\User::where('mobile',$data['phoneNumber'])->find();
            if ($user) {
                if ($user->status != 'normal') {
                    Db::rollback();
                    $this->error(__('Account is locked'));
                }
                //如果已经有账号则直接登录
                $ret = $this->auth->direct($user->id);
            } else {
                $user_config = \app\common\model\xilumarket\Config::getMyConfig('user');
                $extend = [];
                if(isset($user_config['avatar'])){
                    $extend['avatar'] = cdnurl($user_config['avatar'],true);
                }
                $extend['nickname'] = preg_match("/^1[3-9]{1}\d{9}$/", $data['phoneNumber']) ? substr_replace($data['phoneNumber'], '****', 3, 4) : $data['phoneNumber'];
                $ret = $this->auth->register($data['phoneNumber'], Random::alnum(), '', $data['phoneNumber'], $extend);
            }
            if ($ret) {
                $userinfo = $this->auth->getUserinfo();
                #更新third表字段
                $third->user_id = $userinfo['id'];
                $third->save();
//                #创建用户消息表
                UserAccount::addAccount($userinfo['id']);
                $third = ['third_id'=>$third->id,'binding'=>1];
                $data = ['userinfo' => $userinfo,'third'=>$third];
            } else {
                Db::rollback();
                $this->error($this->auth->getError());
            }
        }catch (ThrowableError $e){
            Db::rollback();
            $this->error($e->getMessage());
        }catch (Exception $e){
            Db::rollback();
            $this->error($e->getMessage());
        }
        Db::commit();
        $this->success(__('登录成功'), $data);
    }

    /**
     * 手机验证码登录
     *
     * @ApiMethod (POST)
     * @param string $mobile  手机号
     * @param string $captcha 验证码
     */
    public function mobilelogin()
    {
        $mobile = $this->request->post('mobile');
        $captcha = $this->request->post('code');
        if (!$mobile || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        if (!Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('手机号格式错误'));
        }
        if (!Sms::check($mobile, $captcha, 'mobilelogin')) {
            $this->error(__('验证码错误'));
        }
        $user = \app\common\model\User::getByMobile($mobile);
        if ($user) {
            if ($user->status != 'normal') {
                $this->error(__('账号已被锁定'));
            }
            //如果已经有账号则直接登录
            $ret = $this->auth->direct($user->id);
        } else {
            $extend['nickname'] = preg_match("/^1[3-9]{1}\d{9}$/", $mobile) ? substr_replace($mobile, '****', 3, 4) : $mobile;
            $ret = $this->auth->register($mobile, Random::alnum(), '', $mobile, $extend);
        }
        if ($ret) {
            Sms::flush($mobile, 'mobilelogin');
            $userinfo = $this->auth->getUserinfo();
            #创建用户消息表
            //UserAccount::addAccount($userinfo['id']);
            $data = ['userinfo' => $userinfo];
            $this->success(__('Logged in successful'), $data);
        } else {
            $this->error($this->auth->getError());
        }
    }


    /**
     * 用户信息
     */
    public function info(){
        $user = $this->auth->getUser()->hidden(['group_id','password','salt','level','bio','token','loginip','joinip','jointime','successions','maxsuccessions','prevtime']);
        $user['mobile'] = substr_replace($user['mobile'],'****',3,4);
        #收藏
        $user->collection_count = UserCollection::getCollectionCount($user,[UserCollection::TYPE_PRODUCT,UserCollection::TYPE_FORUM]);
        #关注数
        $user->focus_count = UserFocus::getCount($user);
        #浏览数
        $user->view_count = FooterView::getCount(['user_id'=>$user->id,'type'=>FooterView::TYPE_PRODUCT]);
        #粉丝数
        $user->fans_count = UserFocus::getFocusCount($user->id);
        #帖子
        $user->forum_count = TopicForum::getCount(['user_id'=>$user->id]);
        #圈子
        $user->topic_count = TopicUser::getCount(['user_id'=>$user->id]);

        #闲置商品数
        $user->sale_product_count = ProductModel::getMyProductCount(['product_type'=>1,'check_status'=>2,'status'=>2,'sale_out_status'=>0],$user->id);

        #我卖出的
        $my_sale_pay = \app\common\model\xilumarket\Order::get_count(['pay_status'=>'1','freight_status'=>'0','receipt_status'=>'0','order_status'=>'1','seller_user_id'=>$user->id]);
        $my_sale_aftersale = \app\common\model\xilumarket\Order::get_count(['pay_status'=>'1','refund_status'=>'1','seller_user_id'=>$user->id]);
        $user->sale_order_count = $my_sale_pay+$my_sale_aftersale;

        #我买到的
        $user->buy_order_count = \app\common\model\xilumarket\Order::get_count(['pay_status'=>'1','order_status'=>'1','refund_status'=>['in',['0','3']],'user_id'=>$user->id]);

        #回收
        $user->recovery_count = ProductModel::getMyProductCount(['product_type'=>2,'status'=>2],$user->id);

        //更新活跃度
        $user->allowField("logintime")->save(['logintime'=>time()]);

        $user->is_delivery = !!DeliveryKeyUserRelation::where(['user_id' => $user->id])->find();
        $this->success('查询成功',$user);
    }

    /**
     * @ApiTitle (修改会员个人信息)
     * @ApiRoute (/api/xilumarket.user/profile)
     * @ApiMethod (POST)
     * @ApiHeaders (name=token, type=string, require=true, description="Token")
     * @ApiParams (name="avatar", type="string", required=true, description="头像")
     * @ApiParams (name="nickname", type="string", required=true, description="昵称")
     */
    public function profile()
    {
        $user = $this->auth->getUser();
        $user->visible(['bio','avatar','nickname','mobile','auth']);
        #认证信息
        $auth = UserAuth::isAuth($user->id);
        if($auth){
            $auth->idcard_no = substr_replace($auth->idcard_no,'******',-6,6);
        }
        $user->auth = $auth;
        if($this->request->isPost()) {
            $nickname = $this->request->post('nickname');
            $avatar = $this->request->post('avatar', '', 'trim,strip_tags,htmlspecialchars');
            $bio = $this->request->post('bio');
            $user->nickname = $nickname;
            $user->avatar = $avatar;
            $user->bio = $bio;
            $user->allowField(['avatar','nickname','bio'])->save();

            //更新认证
//            $params = $this->request->only(['username','idcard_no','idcard_type','idcard_face_image','idcard_back_image']);
//            try {
//                $ret = UserAuth::apply($params,$user->id);
//            }catch (Exception|PDOException $e){
//                $this->error($e->getMessage());
//            }

            $this->success('', $user);
        }
        $this->success('',$user);
    }

    /**
     * 我的关注
     */
    public function myfocus(){
        $params = $this->request->param('');
        $this->success('查询成功',UserFocus::getFocusUser($params,$this->auth->id));
    }

    /**
     * 足迹
     */
    public function footer_view(){
        $params = $this->request->param('');
        $this->success('查询成功',FooterView::lists($params,$this->auth->id));
    }
    /**
     * 认证
     */
    public function auth(){
        $user_id = $this->auth->id;
        $params = $this->request->post('');
        try {
            $ret = UserAuth::apply($params,$user_id);
        }catch (Exception|PDOException $e){
            $this->error($e->getMessage());
        }
        $this->success('',$ret);
    }

    /**
     * 判断我是否有认证
     */
    public function my_auth(){
        $auth = UserAuth::isAuth($this->auth->id);
        $this->success('',$auth);
    }

    /**
     * 我的圈子
     */
    public function my_topic(){
        $params = $this->request->param('');
        $pagesize = array_get($params,'pagesize');
        $lists = TopicUser::with(['topic'=>function($q){
            $q->withField(['id','name','image']);
        }])
            ->where('user_id',$this->auth->id)
            ->order('id','desc')
            ->paginate($pagesize)
            ->each(function ($row){
                $row->topic && $row->topic->setAttr('topic_join_count',$row->topic->getTopicUserCount());
            });
        $this->success('查询成功',$lists);
    }

    /**
     * 主页
     */
    public function home(){
        $params = $this->request->param('');
        $user_id = array_get($params,'user_id');
        if(!$user_id){
            $user_id = $this->auth->id;
        }
        if(!$user_id){
            $this->error("参数错误");
        }
        $user = \app\common\model\User::field('id,nickname,avatar,bio')->where('id',$user_id)->find();
        #关注数
        $user->focus_count = UserFocus::getCount($user);
        #粉丝数
        $user->fans_count = UserFocus::getFocusCount($user->id);
        #关注
        $user->is_focus_count = UserFocus::isFocus($this->auth->id,$user_id);
        $this->success('',$user);
    }

    /**
     * 主页-宝贝
     */
    public function home_product(){
        $params = $this->request->param('');
        $user_id = array_get($params,'user_id');
        if(!$user_id){
            $user_id = $this->auth->id;
        }
        if(!$user_id){
            $this->error("参数错误");
        }
        $result = ProductModel::homeLists($params,$user_id);
        $this->success('查询成功', $result);
    }

    /**
     * 主页-论坛
     */
    public function home_forum(){
        $params = $this->request->param('');
        $user_id = array_get($params,'user_id');
        if(!$user_id){
            $user_id = $this->auth->id;
        }
        if(!$user_id){
            $this->error("参数错误");
        }
        $result = TopicForum::homeLists($params,$user_id,$this->auth->id);
        $this->success('查询成功', $result);
    }

    /**
     * 我的收入
     */
    public function my_income(){
        $row = $this->auth->getUser();
        $user_account = UserAccount::addAccount($row->id);
        $freeze_money = OrderDivide::where('user_id',$row->id)->where('status','1')->sum('order_money');
        $this->success('查询成功',[
            'money'=> $user_account->money,
            'total_money'=>$user_account->total_money,
            'freeze_money'=>bcadd($freeze_money,0,2)
        ]);
    }

    /**
     * 我的收入记录
     */
    public function money_list(){
        $params = $this->request->param('');
        $pagesize = array_get($params,'pagesize');
        $lists = \app\common\model\xilumarket\MoneyLog::where('user_id',$this->auth->id)
            ->order('id','desc')
            ->paginate($pagesize)
            ->each(function ($row){
                $row->extra_text = json_decode($row->extra,true);
            });
        $this->success('查询成功',$lists);
    }

    /**
     * 提现记录
     */
    public function withdraw()
    {
        $params = $this->request->post('');
        try {
            $result = \app\common\model\xilumarket\Withdraw::withdraw($params, $this->auth->getUser());
        } catch (Exception $e) {
            $this->error($e->getMessage());
        }
        $this->success('提现成功', $result);
    }
}